<template>
  <div class="group-assistant-send">
    <!-- 步骤条 -->
    <el-steps
      class="group-send-steps"
      align-center
      :active="currentStep"
      :process-status="currentStepStatus"
      finish-status="success"
    >
      <el-step title="选择好友" icon="el-icon-s-check"></el-step>
      <el-step title="设置标签" icon="el-icon-edit"></el-step>
    </el-steps>

    <!-- 好友筛选|内容编辑 -->
    <div class="group-send-content">
      <!-- 好友筛选页面 -->
      <div v-if="currentStep === 0" class="chose-friend">
        <div class="chose-friend-left">
          <el-tabs class="scroll can-not-select" type="border-card" v-model="activeTabName">
            <el-tab-pane label="选择好友批量打标签" name="choseFriends">
              <!-- 所在微信 -->
              <div class="el-tab-pane-item">
                <span class="el-tab-pane-item-title">所在微信</span>
                <el-select
                  v-model="wechat2send"
                  clearable
                  placeholder="请选择"
                  @change="queryInfoByWechatId"
                >
                  <el-option
                    v-for="(wechat, index) in wechats"
                    :key="index"
                    :label="wechat.WeChatNick"
                    :value="wechat.WeChatId"
                    :disabled="!wechat.IsOnline || !wechat.IsLogined"
                  ></el-option>
                </el-select>
              </div>
              <!-- 所在分组 -->
              <div class="el-tab-pane-item">
                <span class="el-tab-pane-item-title">所在分组</span>
                <el-select v-model="team2screen" clearable placeholder="请选择" disabled></el-select>
              </div>
              <!-- 性别 -->
              <div class="el-tab-pane-item">
                <span class="el-tab-pane-item-title">性别</span>
                <el-select v-model="gender2screen" clearable placeholder="请选择">
                  <el-option
                    v-for="(item, index) in gender"
                    :key="'gender'+index"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </div>
              <!-- 状态 -->
              <div class="el-tab-pane-item">
                <span class="el-tab-pane-item-title">状态</span>
                <el-select v-model="state2screen" clearable placeholder="请选择" disabled></el-select>
              </div>
              <!-- 标签 -->
              <div class="el-tab-pane-item">
                <span class="el-tab-pane-item-title">标签</span>
                <el-radio-group v-model="lableRadio">
                  <el-radio :label="'inclusion'">包含</el-radio>
                  <el-radio :label="'exclude'">不包含</el-radio>
                </el-radio-group>
              </div>
              <div class="el-tab-pane-item">
                <span class="el-tab-pane-item-title"></span>
                <el-select
                  v-model="labels2screen"
                  multiple
                  filterable
                  :placeholder="wechat2send ? '请选择':'请先选择微信'"
                  :disabled="!wechat2send"
                  collapse-tags
                >
                  <el-option
                    v-for="(item, index) in groupSendLabels"
                    :key="'label'+index"
                    :label="item.LabelName"
                    :value="item.LabelId"
                  ></el-option>
                </el-select>
              </div>
              <!-- 城市 -->
              <div class="el-tab-pane-item">
                <span class="el-tab-pane-item-title">城市</span>
                <el-radio-group v-model="cityRadio">
                  <el-radio :label="'inclusion'">包含</el-radio>
                  <el-radio :label="'exclude'">不包含</el-radio>
                </el-radio-group>
              </div>
              <div class="el-tab-pane-item">
                <span class="el-tab-pane-item-title"></span>
                <el-cascader
                  v-model="cities"
                  :options="chineseCities"
                  :props="{ expandTrigger: 'hover', multiple: true }"
                  :show-all-levels="false"
                  @change="handleCityChange"
                  filterable
                  collapse-tags
                ></el-cascader>
              </div>
              <!-- 筛选|重置 -->
              <div class="el-tab-pane-item">
                <span class="el-tab-pane-item-title"></span>
                <el-button @click="screenFriends">筛选</el-button>
                <el-button @click="resetFilter">重置</el-button>
              </div>
            </el-tab-pane>
            <el-tab-pane label="选择群并分组" disabled name="choseRooms">
              <!-- 所在微信 -->
              <div class="el-tab-pane-item">
                <span class="el-tab-pane-item-title">所在微信</span>
                <el-select
                  v-model="wechat2send2room"
                  clearable
                  placeholder="请选择"
                  @change="queryInfoByWechatId"
                >
                  <el-option
                    v-for="(wechat, index) in wechats"
                    :key="index"
                    :label="wechat.WeChatNick"
                    :value="wechat.WeChatId"
                    :disabled="!wechat.IsOnline || !wechat.IsLogined"
                  ></el-option>
                </el-select>
              </div>
              <!-- 群名称 -->
              <div class="el-tab-pane-item">
                <span class="el-tab-pane-item-title">群名称</span>
                <el-input placeholder="请输入内容" v-model="room2screen" clearable></el-input>
              </div>
              <div class="el-tab-pane-item">
                <span class="el-tab-pane-item-title"></span>
                <el-button @click="screenRooms">筛选</el-button>
                <el-button @click="resetFilter">重置</el-button>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="chose-friend-right">
          <!-- 数据展示 -->
          <div class="friends-list">
            <el-table
              :data="tableData[currentPage[activeTabName]-1]"
              stripe
              border
              height="60"
              style="width: 100%"
              highlight-current-row
            >
              <el-table-column type="index" :index="indexMethod" label="序号" width="60px"></el-table-column>
              <el-table-column
                label="昵称"
                :prop="activeTabName === 'choseFriends' ? 'FriendNick':'NickName'"
              ></el-table-column>
              <el-table-column v-if="activeTabName === 'choseFriends'" label="备注名" prop="Memo"></el-table-column>
              <el-table-column
                v-if="activeTabName === 'choseFriends'"
                label="性别"
                prop="Gender"
                width="80px"
              ></el-table-column>
              <el-table-column v-if="activeTabName === 'choseFriends'" label="城市" prop="City"></el-table-column>
              <el-table-column v-if="activeTabName === 'choseRooms'" label="群成员人数" width="100px">
                <template slot-scope="scope">
                  <span v-if="activeTabName === 'choseRooms'" v-text="scope.row.MemberList.length"></span>
                </template>
              </el-table-column>
              <!-- 全选 -->
              <!-- <el-table-column type="selection" reserve-selection align="center" width="80px"></el-table-column> -->
              <el-table-column width="100px" align="center">
                <template slot="header">
                  <el-button size="mini" type="primary" @click="choseAllOfPage">全选本页</el-button>
                </template>
                <template slot-scope="scope">
                  <input
                    type="checkbox"
                    :checked="computedCheckState(scope.row)"
                    @click="choseRow(scope.row)"
                  />
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage[activeTabName]"
              :page-sizes="[5, 10, 15, 20]"
              :page-size="pageSize"
              :pager-count="5"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalNum"
            ></el-pagination>
          </div>
        </div>
      </div>
      <!-- 内容编辑页面 -->
      <div v-else-if="currentStep === 1" class="set-label">
        <div class="set-label-item">
          <span class="set-label-item-title">标签名</span>
          <el-select
            v-model="labelId"
            filterable
            :placeholder="wechat2send ? '选择或者输入标签名':'请先选择微信'"
            :disabled="!wechat2send"
            allow-create
            default-first-option
          >
            <el-option
              v-for="(item, index) in groupSendLabels"
              :key="'label'+index"
              :label="item.LabelName"
              :value="item.LabelId"
            ></el-option>
          </el-select>
        </div>
      </div>
    </div>

    <!-- 上一页|发送 -->
    <div class="group-send-operation">
      <el-button
        v-if="currentStep > 0"
        size="small"
        type="primary"
        icon="el-icon-arrow-left"
        @click="currentStep = 0"
      >上一步</el-button>
      <el-button
        v-if="currentStep === 0"
        size="small"
        type="primary"
        @click="sendNext('all')"
      >给所有筛选结果打标签</el-button>
      <el-button
        v-if="currentStep === 0 "
        size="small"
        type="primary"
        @click="sendNext('check')"
      >给选中的好友打标签</el-button>
      <el-button v-if="currentStep === 1 " size="small" type="primary" @click="sureSend">确认发送</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import chineseCities from '@/utils/city.json'

export default {
  name: 'GroupAssistantSend',
  data() {
    return {
      activeTabName: 'choseFriends', // 默认选择好友 choseRooms是选择群聊
      // 分页
      pageSize: 5, // 每页消息数
      currentPage: {
        choseFriends: 1,
        choseRooms: 1
      }, // 当前页
      labelId: '', // 标签id

      // 好友筛选用到的数据
      wechat2send: '', // 要发送的微信
      friends2send: [], // 选中的好友
      team2screen: '', // 要筛选的分组 暂时用不到
      state2screen: '', // 要筛选的状态 暂时用不到
      gender2screen: '', // 要筛选的性别
      lableRadio: 'inclusion', // 标签 包含inclusion,不包含exclude
      labels2screen: [], // 要筛选的标签
      cities: [], // 要筛选的城市
      city2screen: [], // 要筛选的城市
      // 群筛选用到的数据
      wechat2send2room: '', // 要发送的群
      rooms2send: [], // 选中的群
      room2screen: '', // 要筛选的群
      currentStep: 0, // 当前步骤
      currentStepStatus: 'process', // 当前步骤的状态 wait / process / finish / error / success
      cityRadio: 'inclusion', // 城市 包含inclusion,不包含exclude
      // 信息展示用到的数据
      tableDataFriends: [], // 表格中的数据
      totalFriends: 0, // 总的好友
      tableDataRooms: [], // 群聊表格中的数据
      totalRooms: 0, // 总的群聊
      // 性别
      gender: [
        {
          value: 'Male',
          label: '男'
        },
        {
          value: 'Female',
          label: '女'
        }
      ],
      ids2send: [], // 要发送的好友/群id
    }
  },
  computed: {
    ...mapGetters({
      wechats: 'conversation/wechats',
      groupSendRooms: 'nedb/groupSendRooms',
      groupSendLabels: 'nedb/groupSendLabels',
      groupSendFriends: 'nedb/groupSendFriends',
    }),
    // 中国城市数据
    chineseCities() {
      let cities = []
      for (const cityList of chineseCities) {
        let cityChildren = []
        for (const cityName of cityList.list) {
          cityChildren.push({
            value: cityName,
            label: cityName,
          })
        }
        cities.push({
          value: cityList.letter,
          label: cityList.letter,
          children: cityChildren
        })
      }
      return cities
    },
    // 信息总数
    totalNum() {
      if (this.activeTabName === "choseFriends") {
        return this.totalFriends
      } else if (this.activeTabName === "choseRooms") {
        return this.totalRooms
      } else {
        return 0
      }
    },
    // 表格中的数据
    tableData() {
      //   if (this.activeTabName === "choseFriends") {
      //     return this.tableDataFriends
      //   }
      //   return this.tableDataRooms
      // 筛选出来的好友进行分组
      let size = this.pageSize
      let newFriends = []
      if (this.activeTabName === "choseFriends") {
        for (let i = 0; i < this.tableDataFriends.length; i += size) {
          newFriends.push(this.tableDataFriends.slice(i, i + size))
        }
      } else {
        for (let i = 0; i < this.tableDataRooms.length; i += size) {
          newFriends.push(this.tableDataRooms.slice(i, i + size))
        }
      }
      return newFriends
    },
  },
  methods: {
    // 切换tab
    // handleTabClick(tab, event) {
    // },
    // 根据微信id查询数据
    queryInfoByWechatId() {
      if (this.activeTabName === 'choseFriends' && this.wechat2send) {
        this.tableDataFriends = []
        // 查询当前微信的标签
        this.$store.dispatch('nedb/SetGroupSendLabels', this.wechat2send)
        // 查询当前微信的好友
        this.$store.dispatch('nedb/SetGroupSendFriends', this.wechat2send)
      } else if (this.activeTabName === 'choseRooms' && this.wechat2send2room) {
        this.tableDataRooms = []
        // 查询当前微信的群聊
        this.$store.dispatch('nedb/SetGroupSendRooms', this.wechat2send2room)
      }
    },
    // 选择城市
    handleCityChange(value) {
      if (value.length === 0) return
      let nc = []
      for (const item of value) {
        nc.push(item[1])
      }
      this.city2screen = nc
    },
    // 筛选好友
    screenFriends() {
      // 如果没有选择微信 则不做处理
      if (!this.wechat2send) {
        this.$message.warning('请选择微信！')
        return
      }
      let friendsFiltered = []
      // 默认显示全部的好友
      for (const friend of this.groupSendFriends) {
        friendsFiltered.push(friend)
      }
      // 如果要筛选性别
      if (this.gender2screen) {
        friendsFiltered = friendsFiltered.filter((currentValue, index, arr) => {
          return currentValue.Gender === this.gender2screen
        })
      }
      // 如果要筛选标签
      if (this.labels2screen.length > 0) {
        let nfl = []
        for (const iterator of friendsFiltered) {
          let currentLabelIds = []
          if (iterator.LabelIds) {
            currentLabelIds = iterator.LabelIds.replace('"', '[').replace('"', ']').split(',')
          }
          // 交集
          let intersection = this.labels2screen.filter(function (val) { return currentLabelIds.indexOf(val.toString()) > -1 })
          // 是包含还是不包含
          if (this.lableRadio === 'inclusion' && intersection.length > 0) {
            nfl.push(iterator)
          } else if (this.lableRadio === 'exclude' && intersection.length === 0) {
            nfl.push(iterator)
          }
        }
        friendsFiltered = nfl
      }
      // 如果要筛选城市
      if (this.city2screen.length > 0) {
        let nfc = []
        for (const iterator of friendsFiltered) {
          let currentCity = iterator.City ? iterator.City : ''
          // 是包含还是不包含
          if (this.cityRadio === 'inclusion' && this.city2screen.indexOf(currentCity) > -1) {
            nfc.push(iterator)
          } else if (this.cityRadio === 'exclude' && this.city2screen.indexOf(currentCity) === -1) {
            nfc.push(iterator)
          }
        }
        friendsFiltered = nfc
      }
      // 筛选出来的好友进行分组
      //   let size = this.pageSize
      //   let newFriends = []
      //   for (let i = 0; i < friendsFiltered.length; i += size) {
      //     newFriends.push(friendsFiltered.slice(i, i + size))
      //   }
      this.totalFriends = friendsFiltered.length
      //   this.tableDataFriends = newFriends
      this.tableDataFriends = friendsFiltered
    },
    // 筛选群聊
    screenRooms() {
      // 如果没有选择微信 则不做处理
      if (!this.wechat2send2room) {
        this.$message.warning('请选择微信！')
        return
      }
      let roomsFiltered = []
      // 默认显示全部的好友
      for (const room of this.groupSendRooms) {
        roomsFiltered.push(room)
      }
      if (this.room2screen) {
        let nr = []
        for (const room of roomsFiltered) {
          if (room.NickName.indexOf(this.room2screen) > -1) {
            nr.push(room)
          }
        }
        roomsFiltered = nr
      }
      // 筛选出来的好友进行分组
      //   let size = this.pageSize
      //   let newRooms = []
      //   for (let i = 0; i < roomsFiltered.length; i += size) {
      //     newRooms.push(roomsFiltered.slice(i, i + size))
      //   }
      this.totalRooms = roomsFiltered.length
      //   this.tableDataRooms = newRooms
      this.tableDataRooms = roomsFiltered
    },
    // 重置
    resetFilter() {
      if (this.activeTabName === 'choseFriends') {
        this.wechat2send = ""
        this.gender2screen = ""
        this.lableRadio = "inclusion"
        this.labels2screen = []
        this.cities = []
        this.cityRadio = "inclusion"
        this.city2screen = []
        this.tableDataFriends = []
      } else {
        this.wechat2send2room = ""
        this.room2screen = ''
        this.tableDataRooms = []
      }
    },
    // 计算序号
    indexMethod(index) {
      return index + 1;
    },
    // 选择row
    choseRow(row) {
      // 好友
      if (this.activeTabName === 'choseFriends') {
        let friendId = row.FriendId
        let fid = this.friends2send.indexOf(friendId)
        fid >= 0 ? this.friends2send.splice(fid, 1) : this.friends2send.push(friendId)
      } else {
        // 群聊
        let roomId = row.UserName
        let rid = this.rooms2send.indexOf(roomId)
        rid >= 0 ? this.rooms2send.splice(rid, 1) : this.rooms2send.push(roomId)
      }
    },
    // 该row是否被选中
    computedCheckState(row) {
      if (this.activeTabName === 'choseFriends') {
        return this.friends2send.indexOf(row.FriendId) >= 0
      }
      return this.rooms2send.indexOf(row.UserName) >= 0
    },
    // 本页全选
    choseAllOfPage() {
      let rows = this.tableData[this.currentPage[this.activeTabName] - 1]
      if (this.activeTabName === 'choseFriends') {
        let rowsArry = rows.map((x) => x.FriendId)
        let intersection = this.friends2send.filter(function (val) { return rowsArry.indexOf(val) > -1 })
        if (intersection.length === rowsArry.length) {
          for (const row of rows) {
            let friendId = row.FriendId
            let fid = this.friends2send.indexOf(friendId)
            this.friends2send.splice(fid, 1)
          }
        } else {
          for (const row of rows) {
            let friendId = row.FriendId
            let fid = this.friends2send.indexOf(friendId)
            if (fid < 0) {
              this.friends2send.push(friendId)
            }
          }
        }
      } else {
        let rowsArry = rows.map((x) => x.UserName)
        let intersection = this.rooms2send.filter(function (val) { return rowsArry.indexOf(val) > -1 })
        if (intersection.length === rowsArry.length) {
          for (const row of rows) {
            let roomId = row.UserName
            let rid = this.rooms2send.indexOf(roomId)
            this.rooms2send.splice(rid, 1)
          }
        } else {
          for (const row of rows) {
            let roomId = row.UserName
            let rid = this.rooms2send.indexOf(roomId)
            if (rid < 0) {
              this.rooms2send.push(roomId)
            }
          }
        }
      }
    },
    // 修改pageSize
    handleSizeChange(val) {
      if (this.pageSize === val) return
      this.pageSize = val
    },
    // 修改当前页
    handleCurrentChange(val) {
      this.currentPage[this.activeTabName] = val
    },
    // 重置表单
    resetForm(msgType) {
      if (msgType === "Link") {
        this.$refs['linkDialog'].resetFields();
      } else {
        this.$refs['weappDialog'].resetFields();
      }
    },
    // 群发全部/群发所选
    sendNext(flag) {
      let ids = []
      if (flag === 'all') {
        if (this.activeTabName === 'choseFriends') {
          ids = this.tableDataFriends.map((val) => {
            return val.FriendId
          })
        } else {
          ids = this.tableDataRooms.map((val) => {
            return val.UserName
          })
        }
      } else {
        if (this.activeTabName === 'choseFriends') {
          ids = this.friends2send
        } else {
          ids = this.rooms2send
        }
      }
      if (ids.length > 0) {
        this.ids2send = ids
        this.currentStep = 1
      } else {
        this.$message.warning('请先选择要发送的好友！')
      }
    },
    // 确认群发
    sureSend() {
      let labelIdMap = {}
      for (const label of this.groupSendLabels) {
        labelIdMap[label.LabelId] = label.LabelName
      }
      let msg = {
        WeChatId: this.wechat2send, // 商家所属微信号
        AddList: this.ids2send.join(','), // 新增的wxid，用,分隔
        LabelId: labelIdMap[this.labelId] ? this.labelId : 0, // 标签id，0则新建标签（如存在同名标签则会失败）
        LabelName: labelIdMap[this.labelId] ? labelIdMap[this.labelId] : this.labelId, // 标签名 id!=0 会设置为该标签名
        // DelList: 5, // 删除的wxid，用,分隔
        // taskId: 6,
      }
      // 没有内容不能发送
      if (msg.LabelName) {
        this.$store.dispatch('websocket/ContactLabelTask', msg)
        this.$message.success('群发好友任务,已经下发!')
        this.labelId = ''
      } else {
        this.$message.warning('请先设置标签！')
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.group-assistant-send {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-content: center;
  justify-content: space-between;
  //   border: solid red 1px;

  ::v-deep .group-send-steps {
    // border-bottom: $border-color-1 solid 2px;
    .el-step__icon {
      .el-step__icon-inner {
        font-size: 24px;
      }
    }
    .el-step__main {
      .el-step__title {
        font-size: 14px;
        font-weight: 300px;
      }
    }
  }

  .group-send-content {
    flex: 1 1 auto;
    border-bottom: $border-color-1 solid 2px;
    padding: 5px;
    overflow: hidden;

    .chose-friend {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: space-between;
      overflow: hidden;
      .chose-friend-left {
        overflow: hidden;
        width: 48%;
        height: 100%;
        .el-tabs {
          height: 100%;
          overflow: hidden;
          overflow-y: scroll;
        }
        .el-tabs__content {
          .el-tab-pane {
            .el-tab-pane-item {
              margin: 10px;
              display: flex;
              align-items: center;
              padding: 5px;
              ::v-deep .el-input {
                // width: 300px;
                min-width: 250px;
                max-width: 50%;
              }
              .el-tab-pane-item-title {
                width: 80px;
                text-align: end;
                display: inline-block;
                margin-right: 15px;
              }
              .el-radio-group {
                padding: 5px;
              }
            }
            .el-tab-pane-btns {
              border: solid red 1px;
              text-align: center;
              margin-left: 80px;
            }
          }
        }
      }
      .chose-friend-right {
        width: 48%;
        height: 100%;
        .friends-list {
          height: 100%;
          display: flex;
          flex-direction: column;
          align-items: center;
          overflow: hidden;
          ::v-deep .el-table {
            .el-table__header
              .el-table-column--selection
              .cell
              .el-checkbox:after {
              color: #333;
              content: "全选";
              font-size: 14px;
              margin-left: 4px;
              font-weight: bold;
            }
          }
          .el-pagination {
            margin: 5px 0;
          }
        }
      }
    }

    .set-label {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      //   border: solid red 1px;
      .set-label-item {
        display: flex;
        align-items: center;
        padding: 10px;
        .set-label-item-title {
          width: 80px;
          font-weight: bold;
          margin-right: 10px;
        }
      }
    }
  }

  .group-send-operation {
    width: 100%;
    // padding: 5px;
    padding: 7px 15px 5px;
    // margin-right: 15px;
    display: flex;
    justify-content: flex-end;
    // border: solid red 1px;
  }

  .el-dialog-content {
    ::v-deep .el-dialog {
      width: 500px;
    }
    .set-type {
      display: flex;
      align-items: center;

      .set-type-span {
        width: 110px;
        // text-align: end;
        padding-right: 12px;
        font-weight: bold;
      }
    }
    .set-content {
      margin: 20px 0 5px 0;
      display: flex;
      flex-direction: column;
      align-items: center;

      ::v-deep .hide .el-upload--picture-card {
        display: none;
      }
      .we-app {
        width: 100%;
      }
    }
    .tips {
      color: #f5a623;
      margin-top: 10px;
    }
  }
}
</style>
